<template>
  <n-drawer
    v-model:show="modelValue.toEdit"
    :width="502"
    :height="500"
    :placement="'bottom'"
  >
    <n-drawer-content
      :title="toADDFlag ? '添加' : '修改'"
      closable
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
        :size="'medium'"
        label-placement="left"
        label-width="auto"
        require-mark-placement="right-hanging"
        :style="{ maxWidth: '640px' }"
      >
        <n-form-item
          label="名字"
          path="name"
        >
          <n-input
            v-model:value="formValue.name"
            placeholder="输入名字"
          />
        </n-form-item>
        <n-form-item>
          <n-button
            attr-type="button"
            @click="handleValidateClick"
          >
            {{ toADDFlag ? "添加" : "修改" }}
          </n-button>
        </n-form-item>
      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script lang="ts" setup generic="T extends object & { toEdit: boolean,toDelete:boolean,toDealRowId: number|undefined}">
import { FieldContentData, FieldIdData } from "@model/fieldTree";
import type { SurfaceSetting } from "@model/surfaceSetting";
import UseFieldTree from "@pinias/UseFieldTree";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import pinia from "@pinias/pinia";
import { StageIdsInit } from "@utils/pathUtils";
import { NForm, NFormItem, NInput, NDrawer, NDrawerContent, NButton, FormInst } from "naive-ui";
import { ref, computed, watch } from "vue";

// 全局数据
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting: SurfaceSetting = getSurfaceSetting();
const { getFieldTree } = UseFieldTree(pinia);
const fieldTree = getFieldTree();

// 父组件数据
const props = defineProps<{ modelValue: T }>();
const emit = defineEmits(["update:modelValue"]);
const modelValue = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val),
});

// 页面数据
const toADDFlag = computed(() => {
  return typeof modelValue.value.toDealRowId == "undefined";
});
const rules = {
  name: {
    required: true,
    message: "请输入名字",
    trigger: ["input"],
  },
};
const formRef = ref<FormInst | null>(null);
const getNewFormValue = () => {
  // console.log('getNewFormValue',toDealField);
  const nullModel = {
    id: surfaceSetting.maxId,
    name: "",
  };
  if (toADDFlag.value) {
    return nullModel;
  } else {
    const id = modelValue.value.toDealRowId;
    const oldData = fieldTree.getFieldDataById(id);
    if (oldData === undefined) return nullModel;
    else
      return {
        id: oldData.id,
        name: oldData.topic,
      };
  }
};
const formValue = ref(getNewFormValue());
// console.log('formValue',formValue.value);
watch(
  //也可以第一参数为响应式数据
  modelValue.value,
  () => {
    formValue.value = getNewFormValue();
  },
);

// 添加逻辑
const addNew = () => {
  const tosave = formValue.value;
  if (toADDFlag.value) {
    fieldTree.addFieldData(new FieldContentData(tosave.id, tosave.name, StageIdsInit()));
    fieldTree.addFieldIdData(new FieldIdData(tosave.id, []));
    surfaceSetting.maxId++;
  } else {
    const temp = fieldTree.getFieldDataById(tosave.id);
    if (temp !== undefined) temp.topic = tosave.name;
  }
  // formValue = getNewFormValue();
  surfaceSetting.FieldTreeKey = new Date().getTime();
};
const handleValidateClick = (e: MouseEvent) => {
  // console.log('toDealRow',toDealRow);
  e.preventDefault();
  formRef.value?.validate((errors: any) => {
    if (!errors) {
      // message.success("Valid");
      addNew();
      modelValue.value.toEdit = false;
    } else {
      console.log(errors);
      // message.error("Invalid");
    }
  });
};
</script>

<style scoped></style>
